package com.mars.diancan.converter;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.mars.diancan.common.ResultEnum;
import com.mars.diancan.dto.OrderDTO;
import com.mars.diancan.exception.DiancanException;
import com.mars.diancan.form.OrderForm;
import com.mars.diancan.pojo.OrderDetail;
import com.mars.diancan.pojo.OrderMaster;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * OrderForm to OrderDTO 转换器
 * @author MARS
 * @date 2018/6/25
 */
@Slf4j
public class OrderForm2OrderDTOConverter {

    public static OrderDTO converter(OrderForm orderForm){
        Gson gson = new Gson();

        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setBuyerName(orderForm.getName());
        orderDTO.setBuyerPhone(orderForm.getPhone());
        orderDTO.setBuyerAddress(orderForm.getAddress());
        orderDTO.setBuyerOpenid(orderForm.getOpenid());

        // 将json转换成list,参数1：要转化的string字符，参数2：通过TypeToken映射成新定义的类型
        List<OrderDetail> orderDetailList = new ArrayList<>();
        try {
            orderDetailList = gson. fromJson(orderForm.getItems(),new TypeToken<List<OrderDetail>>(){}.getType());
        } catch (JsonSyntaxException e) {
            log.error("对象转化错误，string={}",orderForm.getItems());
            throw new DiancanException(ResultEnum.PARAM_ERROR);
        }
        orderDTO.setOrderDetailList(orderDetailList);
        return orderDTO;
    }

}
